import { writeFileSync } from 'fs';
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './exceptions/http-exception.filter';
import { TransformInterceptor } from './interceptors/transform.interceptor';
import { JwtAuthGuard } from './auth/jwt-auth.guard';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 注册全局接口参数验证
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
      stopAtFirstError: true,
      skipMissingProperties: false, // 确保所有的属性都被验证
    }),
  );
  // 注册全局过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
  // 注册全局拦截器
  app.useGlobalInterceptors(new TransformInterceptor());

  const swaggerOptions = new DocumentBuilder()
    .setTitle('cms-project api')
    .setDescription('内容管理系统描述')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  SwaggerModule.setup('api-docs', app, document);

  // 将 Swagger 文档保存为 JSON 文件
  writeFileSync('./swagger.json', JSON.stringify(document, null, 2), 'utf8');

  // 更换日志记录器
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));

  // JWT路由守卫
  app.useGlobalGuards(app.get(JwtAuthGuard));

  await app.listen(3000);
}
bootstrap();
